package com.zdkj.subway.st.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.core.exceltools.IExcelExport;
import com.zdkj.common.core.util.R;
import com.zdkj.common.core.util.SpringContextHolder;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.dto.in.SwStInputPassengerWorkTicketDTO;
import com.zdkj.subway.st.entity.SwStInvalidTicket;
import com.zdkj.subway.st.entity.SwStInvalidTicketProduce;
import com.zdkj.subway.st.entity.SwStPlanDay;
import com.zdkj.subway.st.fegin.SubwayStmService;
import com.zdkj.subway.st.service.SwStInvalidTicketProduceService;
import com.zdkj.subway.st.service.SwStInvalidTicketService;
import com.zdkj.subway.st.service.SwStPlanDayService;
import com.zdkj.subway.st.util.DateUtilsSt;
import com.zdkj.subway.st.util.GenSerialNo;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: zdkj
 * @Package: com.zdkj.subway.st.controller
 * @ClassName: SwStInvalidTicketProduceController
 * @Description:
 * @Author: kangjian
 * @CreateDate: 2020/1/7 11:31
 * @Version: 1.0
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swStInvalidTicketProduce")
@Api(value = "swStInvalidTicketProduce", tags = "无效票生成申请")
public class SwStInvalidTicketProduceController {
    //提交状态  已提交1 已回馈2
    private static final String SUBMIT_ON = "1";
    private static final String SUBMIT_BACK = "2";
    private final SwStInvalidTicketProduceService swStInvalidTicketProduceService;
    private final SwStInvalidTicketService swStInvalidTicketService;//无效票管理
    private final SwStPlanDayService swStPlanDayService;//日生产计划
    private final SubwayStmService subwayStmService;
	@Autowired
    private GenSerialNo genSerialNo;

    @GetMapping("/{id}")
    public R getById(@PathVariable String id) {
        return R.ok(swStInvalidTicketProduceService.getById(id));
    }

    @GetMapping("/page")
    public R<IPage> getDictPage(Page page, SwStInvalidTicketProduce swStInvalidTicketProduce) {
        String oldCardOrder = swStInvalidTicketProduce.getOldCardOrder();
        swStInvalidTicketProduce.setOldCardOrder(null);
        LambdaQueryWrapper<SwStInvalidTicketProduce> lambdaQueryWrapper = Wrappers.query(swStInvalidTicketProduce).orderByDesc("apply_time").lambda();
        String dateCondition = swStInvalidTicketProduce.getApplyTimeDTO();

        if (StringUtils.isNotBlank(dateCondition)) {
            lambdaQueryWrapper.likeRight(SwStInvalidTicketProduce::getApplyTime, dateCondition);
        }
        if (StringUtils.isNotBlank(oldCardOrder)) {
            lambdaQueryWrapper.like(SwStInvalidTicketProduce::getOldCardOrder,oldCardOrder);
        }
        return R.ok(swStInvalidTicketProduceService.page(page, lambdaQueryWrapper));
    }

    @SysLog("无效票生产申请保存信息")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('st_invalid_ticket_produce_add')")
    public R save(@Valid @RequestBody SwStInvalidTicketProduce swStInvalidTicketProduce) {
        PigxUser user = SecurityUtils.getUser();
        swStInvalidTicketProduce.setCreatorName(user.getNikeName());
        swStInvalidTicketProduce.setCreatorId(user.getId());
        swStInvalidTicketProduce.setTicketSource("手动新增");
        return R.ok(swStInvalidTicketProduceService.save(swStInvalidTicketProduce));
    }

    @PostMapping("/inner")
    @Inner
    public R feignSave(@Valid @RequestBody SwStInvalidTicketProduce swStInvalidTicketProduce) {
        return R.ok(swStInvalidTicketProduceService.save(swStInvalidTicketProduce));
    }

    @SysLog("删除无效票生产申请信息")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('st_invalid_ticket_produce_delete')")
    public R removeById(@PathVariable String id) {
        return R.ok(swStInvalidTicketProduceService.removeById(id));
    }

    @PutMapping
    @SysLog("修改无效票生产申请信息")
    @PreAuthorize("@pms.hasPermission('st_invalid_ticket_produce_update')")
    public R updateById(@Valid @RequestBody SwStInvalidTicketProduce swStInvalidTicketProduce) {
        PigxUser user = SecurityUtils.getUser();
        swStInvalidTicketProduce.setCreatorName(user.getNikeName());
        swStInvalidTicketProduce.setCreatorId(user.getId());
        return R.ok(swStInvalidTicketProduceService.updateById(swStInvalidTicketProduce));
    }

    @PutMapping("/submit")
    @SysLog("提交无效票管理信息")
    @PreAuthorize("@pms.hasPermission('st_invalid_ticket_produce_submit')")
    public R submitByIds(@RequestBody List<SwStInvalidTicketProduce> ids) {
        ids.stream().forEach(s -> s.setCheckStatus(SUBMIT_ON));
        return R.ok(swStInvalidTicketProduceService.updateBatchById(ids));
    }

    @PutMapping("/submitBatch")
    @SysLog("提交无效票生产申请信息")
    @PreAuthorize("@pms.hasPermission('st_invalid_ticket_produce_submitBatch')")
    public R submitBatch    (@RequestBody List<SwStInvalidTicketProduce> ids) {
        ids.stream().forEach(s -> s.setSubmitStatus("1"));
        return R.ok(swStInvalidTicketProduceService.updateBatchById(ids));
    }

    @PutMapping("/audit")
    @SysLog("审核无效票管理信息")
    @PreAuthorize("@pms.hasPermission('st_invalid_ticket_produce_audit')")
    public R auditByIds(@RequestBody List<SwStInvalidTicketProduce> ids) {
        boolean b = swStInvalidTicketProduceService.updateBatchById(ids);
        if(b){
            List<SwStPlanDay> swStPlanDayAList = new ArrayList<>();
            List<SwStInputPassengerWorkTicketDTO> workTicketDTOList = new ArrayList<>();
            List<SwStInputPassengerWorkTicketDTO> workTicketList = new ArrayList<>();
            ids.forEach(item -> {
                SwStInvalidTicketProduce swStInvalidTicketProduce = swStInvalidTicketProduceService.getById(item);
                String oldCardOrder = swStInvalidTicketProduce.getOldCardOrder();
                LambdaQueryWrapper<SwStInvalidTicket> LambdaQueryWrapper = new LambdaQueryWrapper<>();
                LambdaQueryWrapper.eq(SwStInvalidTicket::getStationLine,swStInvalidTicketProduce.getStationLine())
                        .eq(SwStInvalidTicket::getStationCode,swStInvalidTicketProduce.getStationCode())
                        .eq(SwStInvalidTicket::getOldCardOrder,oldCardOrder)
                        .eq(SwStInvalidTicket::getApplyTime,swStInvalidTicketProduce.getApplyTime())
                        .eq(SwStInvalidTicket::getCheckStatus,"1")
                        .eq(SwStInvalidTicket::getDelFlag,"0");
                SwStInvalidTicket swStInvalidTicketServiceOne = new SwStInvalidTicket();
                List<SwStInvalidTicket> swStInvalidTicket = swStInvalidTicketService.list(LambdaQueryWrapper);
                if(swStInvalidTicket.size()>0){
                    swStInvalidTicketServiceOne = swStInvalidTicket.get(0);
                }
                if (ObjectUtil.isNotEmpty(swStInvalidTicketServiceOne)){
                    swStInvalidTicketServiceOne.setCheckStatus(swStInvalidTicketProduce.getCheckStatus());
                    swStInvalidTicketServiceOne.updateById();
                }

                //生产日计划
                if(swStInvalidTicketProduce.getCheckStatus().equals("2")){
                    SwStPlanDay swStPlanDay = new SwStPlanDay();
                    PigxUser user = SecurityUtils.getUser();
					//单号生成规则
					String generateNum = genSerialNo.generateNum("L2");
                    swStPlanDay.setNumbers(generateNum);
                    swStPlanDay.setWorkTime(String.valueOf(swStInvalidTicketProduce.getApplyTime().getYear()));//年
                    swStPlanDay.setPlanMonth(String.valueOf(swStInvalidTicketProduce.getApplyTime().getMonthValue()));//月
                    swStPlanDay.setPlanWeek(DateUtilsSt.whatWeek(DateUtilsSt.StringToLocalDate(swStInvalidTicketProduce.getApplyTime())));//周
                    swStPlanDay.setTicketType(swStInvalidTicketProduce.getTicketType());
                    swStPlanDay.setTicketName(swStInvalidTicketProduce.getTicketName());
                    swStPlanDay.setLineCode(swStInvalidTicketProduce.getStationLine());
                    swStPlanDay.setStationCode(swStInvalidTicketProduce.getStationCode());
                    swStPlanDay.setTicketPrice(swStInvalidTicketProduce.getTicketPriceRemain());
                    swStPlanDay.setTicketTimes(swStInvalidTicketProduce.getTicketTimesRemain());
                    swStPlanDay.setActiveTime(swStInvalidTicketProduce.getActiveTime());//新发票卡有效期
                    swStPlanDay.setPlanFinishTime(DateUtilsSt.TimestampToLocalDateTime(DateUtilsSt.LocalDateToTimestamp(swStInvalidTicketProduce.getApplyTime())));//申请时间
                    swStPlanDay.setLatestStartTime(DateUtilsSt.newLocalDateTime());//最晚启动日期
                    swStPlanDay.setTicketNumber(1);//车票张数默认1张

                    swStPlanDay.setPlanType("2");//生产计划类型
                    swStPlanDay.setDisplay(true);
                    swStPlanDay.setDataSource("1");//数据来源无效票
                    swStPlanDay.setCheckStatus("0");
                    swStPlanDay.setCreatorName(user.getNikeName());
                    swStPlanDay.setCreatorId(user.getId().longValue());
                    swStPlanDayAList.add(swStPlanDay);
                }
				/*
                if(swStPlanDayAList.size()>0){
                    swStPlanDayService.saveBatch(swStPlanDayAList);
                }*/

                //乘客事务退换票非即时数据来源——线网
                if(swStInvalidTicketProduce.getCheckStatus().equals("2") && "1".equals(swStInvalidTicketProduce.getDataSource())){
                    SwStInputPassengerWorkTicketDTO swStInputPassengerWorkTicketDTO = new SwStInputPassengerWorkTicketDTO();
                    swStInputPassengerWorkTicketDTO.setOperationType("1");//非即时退换票
                    swStInputPassengerWorkTicketDTO.setHandleType("1");//换票
                    swStInputPassengerWorkTicketDTO.setTicketType(swStInvalidTicketProduce.getTicketType());
                    swStInputPassengerWorkTicketDTO.setTicketName(swStInvalidTicketProduce.getTicketName());
                    swStInputPassengerWorkTicketDTO.setLineCode(swStInvalidTicketProduce.getStationLine());
                    swStInputPassengerWorkTicketDTO.setStationCode(swStInvalidTicketProduce.getStationCode());
                    swStInputPassengerWorkTicketDTO.setCardOrder(swStInvalidTicketProduce.getOldCardOrder());
                    swStInputPassengerWorkTicketDTO.setClassNumber(swStInvalidTicketProduce.getClassNumber());
                    swStInputPassengerWorkTicketDTO.setActiveTime(swStInvalidTicketProduce.getActiveTime());//新发票卡有效期
                    swStInputPassengerWorkTicketDTO.setEstimatedNumber(String.valueOf(swStInvalidTicketProduce.getTicketTimesRemain()));
                    swStInputPassengerWorkTicketDTO.setHandleTime(DateUtilsSt.TimestampToLocalDateTime(DateUtilsSt.LocalDateToTimestamp(swStInvalidTicketProduce.getApplyTime())));
                    swStInputPassengerWorkTicketDTO.setSubmitStatus("0");//未提交
                    swStInputPassengerWorkTicketDTO.setConfirmStatus("0");//客值未确认
                    swStInputPassengerWorkTicketDTO.setInvalidTicketStatus(CommonConstants.INSEND);//无效票状态已发送
                    swStInputPassengerWorkTicketDTO.setInvalidTicketConfirmStatus(CommonConstants.INCHECK);//审核通过
                    swStInputPassengerWorkTicketDTO.setDataSource(swStInvalidTicketProduce.getDataSource());//数据来源：0车站--1线网
                    swStInputPassengerWorkTicketDTO.setHandlePersonCode(swStInvalidTicketProduce.getCardIssuerId());
                    swStInputPassengerWorkTicketDTO.setHandlePersonName(swStInvalidTicketProduce.getCardIssuer());
                    swStInputPassengerWorkTicketDTO.setDeptId(swStInvalidTicketProduce.getDeptId());
                    swStInputPassengerWorkTicketDTO.setCreatorId(swStInvalidTicketProduce.getCreatorId());
                    swStInputPassengerWorkTicketDTO.setCreatorName(swStInvalidTicketProduce.getCreatorName());

                    workTicketDTOList.add(swStInputPassengerWorkTicketDTO);
                }
                /*if(workTicketDTOList.size()>0){
                    subwayStmService.inputPassengerWorkTicketSave(SecurityConstants.FROM_IN,workTicketDTOList);//线网批量添加无效票到车站
                }*/
                //乘客事务退换票非即时数据来源——车站
                if("0".equals(swStInvalidTicketProduce.getDataSource())){
                    SwStInputPassengerWorkTicketDTO swStInputPassengerWorkTicketDTO = new SwStInputPassengerWorkTicketDTO();
                    swStInputPassengerWorkTicketDTO.setCardOrder(swStInvalidTicketProduce.getOldCardOrder());//旧卡号

                    if("2".equals(swStInvalidTicketProduce.getCheckStatus())){
                        swStInputPassengerWorkTicketDTO.setInvalidTicketConfirmStatus(CommonConstants.INCHECK);//审核通过
                    }else {
                        swStInputPassengerWorkTicketDTO.setInvalidTicketConfirmStatus(CommonConstants.UN_INCHECK);//审核不通过
                    }
                    workTicketList.add(swStInputPassengerWorkTicketDTO);
                }
                /*if(workTicketList.size()>0){
                    subwayStmService.inputPassengerWorkTicketUpdateBach(SecurityConstants.FROM_IN,workTicketList);//车站批量修改无效票到车站审批状态
                }*/

            });
			if(swStPlanDayAList.size()>0){
                    swStPlanDayService.saveBatch(swStPlanDayAList);
            }
			if(workTicketDTOList.size()>0){
                    subwayStmService.inputPassengerWorkTicketSave(SecurityConstants.FROM_IN,workTicketDTOList);//线网批量添加无效票到车站
            }
			if(workTicketList.size()>0){
                    subwayStmService.inputPassengerWorkTicketUpdateBach(SecurityConstants.FROM_IN,workTicketList);//车站批量修改无效票到车站审批状态
            }


        }
        return R.ok();
    }

    @SysLog("批量删除无效票管理信息")
    @DeleteMapping("/delBatch")
    @PreAuthorize("@pms.hasPermission('st_invalid_ticket_produce_deletes')")
    public R removeByIds(@RequestBody List<Integer> ids) {
        return R.ok(swStInvalidTicketProduceService.removeByIds(ids));
    }

    @GetMapping("/export")
    @SysLog("导出无效票生产申请信息")
    @PreAuthorize("@pms.hasPermission('st_invalid_ticket_produce_export')")
    public void exportExcel(SwStInvalidTicketProduce swStInvalidTicketProduce, HttpServletResponse response) {
        List<SwStInvalidTicketProduce> swStInvalidTicketProducelist = swStInvalidTicketProduceService.list(Wrappers.query(swStInvalidTicketProduce));
        IExcelExport excelExport = SpringContextHolder.getBean("commonExcelExport");
        Workbook workbook = excelExport.parse(swStInvalidTicketProducelist);
        try {
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            log.error("", e);
        } finally {
        }
    }

}
